const express = require('express');
const router = express.Router();
const ListsModel = require('../../db/modules/lists');
const dayjs = require('dayjs')
const checkToken = require('../../middleWares/checkToken')

// 查
router.get('/list', checkToken, function(req, res, next) {
  ListsModel.find({}).sort({time:-1}).then((result) => {
    // console.log('获取成功',result);
    res.json({
      code: 0,
      msg: '操作成功',
      data: result
    })
  }).catch((error) => {
    // console.log('获取错误',error);
    res.json({
      code: 500,
      msg: '操作失败',
      data: error
    })
  })
});
router.get('/list/:id', checkToken, function(req, res, next) {
  const _id = req.params.id
  ListsModel.findById({_id}).then((result) => {
    res.json({
      code: 0,
      msg: '操作成功',
      data: result
    })
  }).catch((error) => {
    res.json({
      code: 500,
      msg: '操作失败',
      data: error
    })
  })
})

// 增
router.post('/list-create', checkToken, function(req, res, next) {
  let msg = ''
  let code = 400
  if (!req.body.title) {
    msg = 'title为必填项'
  } else if (!req.body.type) {
    msg = 'type为必填项'
  } else if (!req.body.account) {
    msg = 'account为必填项'
  } else if (!dayjs(req.body.time).isValid()) {
    msg = 'time格式错误'
  } else {
    code = 500
    msg = '服务器错误'
  }
  ListsModel.create({
    ...req.body,
    time:dayjs(req.body.time).format('YYYY-MM-DD')
  }).then((result) => {
    // console.log('创建成功',result);
    res.json({
      code: 0,
      msg: '操作成功',
      data: result
    })
  }).catch((error) => {
    // console.log('创建错误',error);
    // res.status(500).send(error)
    res.json({
      code,
      msg,
      data: error
    })
  })
})

// 删
router.delete('/list-delete/:id', checkToken, function(req, res, next) {
  const _id = req.params.id
  ListsModel.deleteOne({_id}).then((result) => {
    res.json({
      code: 0,
      msg: '操作成功',
      data: result
    })
  }).catch((error) => {
    res.json({
      code: 500,
      msg: '操作失败',
      data: error
    })
  })
})

// 改
router.patch('/list-update/:id', checkToken, function(req, res, next) {
  const _id = req.params.id
  ListsModel.updateOne({_id},req.body).then((result) => {
    ListsModel.findById({_id}).then((list) => {
      res.json({
        code: 0,
        msg: '操作成功',
        data: list
      })
    }).catch((error) => {
      res.json({
        code: 500,
        msg: '操作失败',
        data: error
      })
    })
  }).catch((error) => {
    res.json({
      code: 500,
      msg: '操作失败',
      data: error
    })
  })
})

module.exports = router;
